package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.itheima.pojo.*;
import com.itheima.service.FeedbackService;
import com.itheima.service.UserService;
import com.itheima.utils.CookieUtils;
import com.itheima.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/oauth")
public class WebLoginController {


    @Autowired
    private FeedbackService feedbackService;

    @Autowired
    private UserService userService;

    //1.POST /oauth/addFeedback (feedbackVO) 提交反馈
     @PostMapping("/addFeedback")
     public Result addFeedback(FeedbackVO feedbackVO, HttpServletRequest request){
       //获取当前用户的uid

         try {
             Map<String, Object> userInfo = TokenUtil.getUserInfo(request);
             String  userUid = (String)userInfo.get("uid");
             feedbackVO.setUserUid(userUid );
             int i= feedbackService.addFeedback(feedbackVO);
              if (i>0){
                  return new Result(StatusCode.OK,"提交反馈成功");
              }
         } catch (Exception e) {
             e.printStackTrace();
         }

         return new Result(StatusCode.OK,"提交反馈失败");
     }

    //2.POST /oauth/delete/{accessToken} 退出登录，删除accessToken
    @PostMapping("delete/{accessToken}")
    public Result delete(HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if ("Authorization".equals(name)) {
                CookieUtils.deleteCookie(name);
            }
        }
        //用户退出， 删除token
        return new Result(StatusCode.OK,"退出成功");
    }

    //3.POST /oauth/editUser (userVO) 编辑用户信息
    @PostMapping("/editUser")
    public Result editUser(UserVO userVO) {
        try {
            int i= userService.edit(userVO);
            if (i>0){
                return new Result(StatusCode.OK,"操作成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(StatusCode.OK,"操作失败");
    }

    //4.GET /oauth/getFeedbackList 获取用户反馈
    @RequestMapping("/getFeedbackList")
    public Map<String,Object> getList(@RequestBody FeedbackVO feedbackVO){
        PageInfo pageInfo = feedbackService.getList(feedbackVO);
        //封装返回数据
        Map<String,Object> result=new HashMap<>();
        result.put("code","success");
        //封装data
        Map<String,Object> data=new HashMap<>();
        //封装查询出的数据dataList
        List<Map> dataList=new ArrayList<>();
        List list = pageInfo.getList();
        for (Object o : list) {
            Map map = JSON.parseObject(JSON.toJSONString(o), Map.class);
            User user = userService.getUserByUid((String) map.get("userUid"));
            map.put("user",user);
            dataList.add(map);
        }
        data.put("records",dataList);
        data.put("total",pageInfo.getTotal());
        data.put("size",pageInfo.getSize());
        data.put("current",pageInfo.getPageNum());
        data.put("orders","");
        data.put("optimizeCountSql",true);
        data.put("isSearchCount",true);
        //将将data放入返回map
        result.put("data",data);
        return result;
    }

    //5.POST /oauth/updateUserPwd (oldPwd,newPwd) 更新用户密码
    @PostMapping ("/updateUserPwd")
    public  Result updatePassWord(@RequestBody Map map, HttpServletRequest request){
        //查询判断用户是否存在和旧密码是否正确 ，再更新用户密码
        Map<String, Object> userInfo = TokenUtil.getUserInfo(request);
        String  userUid = (String)userInfo.get("uid");
        map.put("uid",userUid);
        User user= userService.findUserBypassWord((String)map.get("oldPwd"));
        if (user==null){
            return new Result(StatusCode.ERROR,"旧密码错误");
        }
        //{"code":"error","data":"旧密码错误"}
        int i = userService.updatePassWord(map);
        if (i>0){
            return new Result(StatusCode.OK,"修改成功");
        }
        return new Result(StatusCode.ERROR,"修改失败");
    }

    //6.GET /oauth/verify/{accessToken} (accessToken)  获取用户信息
    //{"code":"success","data":{"userName":"admin1","passWord":"","nickName":"admin1","email":"159@qq.com","loginCount":0.0,"validCode":"58D526940DCCD7D4237CF00993DE39C5","source":"MOGU","lastLoginTime":"2020-08-10 16:29:10","lastLoginIp":"192.168.71.112","commentStatus":1.0,"startEmailNotification":1.0,"os":"Windows","browser":"Chrome-83.0.4103.97","userTag":0.0,"uid":"892e9a25834dc4b55a2c25c644171e50","status":1.0,"createTime":"2020-05-29 09:34:30","updateTime":"2020-08-10 16:29:10"}}
    @GetMapping("/verify/{accessToken}")
    public  Result info(HttpServletRequest request){

        Map<String, Object> userInfo;
        try {
            userInfo = TokenUtil.getUserInfo(request);
            String username= (String)userInfo.get("username");
            Map<String, Object> map = userService.verify(username);

            return new Result(StatusCode.OK,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(StatusCode.ERROR,null);
        }
    }



}
